<template>
  <div :id="editorId" class="script-screen-parent"></div>
</template>

<script>

import * as monaco from 'monaco-editor'
import YchScriptBuilder from './YchScriptBuilder'

monaco.languages.typescript.javascriptDefaults.addExtraLib(YchScriptBuilder, 'YchScriptBuilder.js');

export default {
  name: 'YchScriptEditor',
  props: {
    value: String,
    disabled: {
      type: Boolean,
      default: false
    },
    language: {
      type: String,
      required: true,
    },
    showSave: {
      type: Boolean,
      default: false
    },
    theme: {
      type: String,
      default: 'vs' // "vs" | "vs-dark" | "hc-black" | "hc-light"
    },
    minimapEnabled: {
      type: Boolean,
      default: true
    },
  },
  data() {
    return {
      editorId: Math.random().toString(36).slice(-8),
      editor: null,
      codeValue: this.value,
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      this.editor = monaco.editor.create(document.getElementById(this.editorId), {
        value: this.codeValue || '',
        language: this.language,
        theme: this.theme,
        autoIndent: true, // 自动缩进
        readOnly: this.disabled,
        minimap: {
          enabled: this.minimapEnabled
        },
        automaticLayout: true, // 自适应布局
        overviewRulerBorder: false, // 不要滚动条的边框
        scrollBeyondLastLine: false, // 取消代码后面一大段空白
      });
      this.editor.onDidChangeModelContent(event => {
        this.codeValue = this.editor.getValue()
      })
      if (this.showSave) {
        this.editor.addAction({
          id: 'Save Script', // 菜单项 id
          label: 'Save Script', // 菜单项名称
          contextMenuGroupId: '9_cutcopypaste', // 所属菜单的分组
          run: () => {
            this.save()
          },
        })
      }
    },
    save() {
      this.$emit("save")
    }
  },
  watch: {
    codeValue(value) {
      if (this.value !== value) {
        this.$emit('input', value)
        this.$emit('change', value)
      }
    },
    value(value) {
      if (this.codeValue !== value) {
        this.codeValue = value || ''
        this.editor.setValue(this.codeValue)
      }
    }
  },
  model: {
    prop: 'value',
    event: 'change'
  }
}
</script>
<style lang="less">
.script-screen-parent {
  width: 100%;
  height: 98%;
}

.script-screen-parent .overflow-guard {
  border: 1px solid lightgrey;
}
</style>
